using System;

namespace VisualPureBasicIDE.FormDesigner.Implementations
{
    /// <summary>
    /// Manages a single operation in a designer transaction.
    /// </summary>
    internal class DesignerTransaction : System.ComponentModel.Design.DesignerTransaction
    {
        // The host
        private readonly DesignerHost _host;

        public DesignerTransaction(DesignerHost host, string description)
            : base(description)
        {
            _host = host;
            description = description ?? "";
            // Push this descriptions.
            host.Transactions.Push(description);
            // When we start the first transaction, we have fire
            // the opening and opened events
            if (host.Transactions.Count == 1)
            {
                // We can fire both back to back instread of 
                // pushing and opening and the firing opened
                host.OnTransactionOpening(EventArgs.Empty);
                host.OnTransactionOpened(EventArgs.Empty);
            }
        }

        protected override void OnCancel()
        {
            if (_host != null)
            {
                _host.Transactions.Pop();
                // If this is the last transaction, fire 
                // closing and closed events
                if (_host.Transactions.Count == 0)
                {
                    _host.OnTransactionClosing(false);
                    _host.OnTransactionClosed(false);
                }
            }
        }

        protected override void OnCommit()
        {
            if (_host != null)
            {
                // Pop transaction
                _host.Transactions.Pop();

                // If this is the last transaction to be closed, 
                // fire closing and closed event
                if (_host.Transactions.Count == 0)
                {
                    _host.OnTransactionClosing(true);
                    _host.OnTransactionClosed(true);
                }
            }
        }
    }
}